/*
Copyright (c) 2010 Andi Rustandi Djunaedi andird@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */
package com.appspot.mobileirisnextbus.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.appspot.mobileirisnextbus.client.BusService;
import com.appspot.mobileirisnextbus.shared.Constants;
import com.appspot.mobileirisnextbus.shared.Util;
import com.google.appengine.repackaged.com.google.common.base.Charsets;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class BusServiceImpl extends RemoteServiceServlet implements BusService {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.appspot.mobileirisnextbus.client.BusService#getBuses(java.lang.String
	 * )
	 */
	@Override
	public List<String> getBuses(String busStop)
			throws IllegalArgumentException {
		List<String> listOfBuses = null;

		// Escape data from the client to avoid cross-site script
		// vulnerabilities.
		busStop = Util.escapeHtml(busStop);

		// get result from mobileiris website
		try {
			// get home page
			URL url = new URL(Constants.sbsMobileiris);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setInstanceFollowRedirects(false);

			if (conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
				// home page redirect result, don't follow it,
				// go retrieve list of services
				final String redirectResult = conn
						.getHeaderField(Constants.headerLocation);
				final String nextBusSelectionPage = redirectResult.replace(
						Constants.indexAspx, Constants.svcList + busStop);
				url = new URL(nextBusSelectionPage);
				conn = (HttpURLConnection) url.openConnection();
				conn.setInstanceFollowRedirects(false);

				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					// get list of buses
					final BufferedReader br = new BufferedReader(
							new InputStreamReader(conn.getInputStream(),
									Charsets.UTF_8));
					String line = br.readLine();
					final List<String> resp = new ArrayList<String>(50);
					while (line != null) {
						resp.add(line);
						line = br.readLine();
					}
					listOfBuses = this.getListOfBuses(resp);
				} else {
					// Server returned unexpected HTTP code.
					System.out.println(Constants.msgNotExpected
							+ conn.getResponseCode());
				}
			} else {
				// Server returned unexpected HTTP code.
				System.out.println(Constants.msgNotExpected
						+ conn.getResponseCode());
			}
		} catch (final MalformedURLException e) {
			e.printStackTrace();
		} catch (final IOException e) {
			e.printStackTrace();
		}
		return listOfBuses;
	}

	@Override
	public List<String> getBusTime(final String busStop, final String svc)
			throws IllegalArgumentException {
		List<String> listOfTimes = null;

		// Escape data from the client to avoid cross-site script
		// vulnerabilities.
		final String inputBusStop = Util.escapeHtml(busStop);
		final String inputSvc = Util.escapeHtml(svc);

		// get result from mobileiris website
		try {
			// get home page
			URL url = new URL(Constants.sbsMobileiris);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setInstanceFollowRedirects(false);

			if (conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
				// home page redirect result, don't follow it,
				// go retrieve list of services
				final String redirectResult = conn
						.getHeaderField(Constants.headerLocation);
				final String goToInputPage = redirectResult.replace(
						Constants.indexAspx, Constants.nextBus);
				url = new URL(goToInputPage);
				conn = (HttpURLConnection) url.openConnection();
				conn.setInstanceFollowRedirects(false);

				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					String cookie = conn.getHeaderField(Constants.setCookie);
					cookie = cookie.substring(0, 22);

					// get resp body
					final BufferedReader br = new BufferedReader(
							new InputStreamReader(conn.getInputStream(),
									Charsets.UTF_8));
					String line = br.readLine();
					String resp = Constants.blank;
					while (line != null) {
						if (line.startsWith(Constants.formLineStart)) {
							resp = line;
						}
						line = br.readLine();
					}

					// input busstop and svc no, using POST
					final String postAction = this.getPostAction(resp);
					final String postUrl = goToInputPage.replace(
							Constants.nextBus, postAction);
					url = new URL(postUrl);
					conn = (HttpURLConnection) url.openConnection();
					conn.setRequestProperty(Constants.cookie, cookie);
					conn.setDoOutput(true);
					conn.setRequestMethod(Constants.httpPost);
					conn.setInstanceFollowRedirects(true);

					String out = Constants.blank;
					out += Constants.hiddenEt + Constants.eq + Constants.amp;
					out += Constants.busStopPostParam + Constants.eq
							+ inputBusStop + Constants.amp;
					out += Constants.busSvcParam + Constants.eq + inputSvc
							+ Constants.amp;
					out += Constants.btnGoParam + Constants.eq
							+ Constants.btnGoVal + Constants.amp;
					final BufferedWriter bw = new BufferedWriter(
							new OutputStreamWriter(conn.getOutputStream(),
									Charsets.UTF_8));
					bw.write(out);
					bw.close();

					if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
						// get resp body
						final BufferedReader resultBr = new BufferedReader(
								new InputStreamReader(conn.getInputStream(),
										Charsets.UTF_8));
						String resultLine = resultBr.readLine();
						boolean nextFound = false;
						boolean subsequentFound = false;
						listOfTimes = new ArrayList<String>(2);
						while ((resultLine != null)
								&& (!nextFound || !subsequentFound)) {
							if (resultLine
									.startsWith(Constants.nextBusValStart)) {
								listOfTimes
										.add(this.getNextBusTime(resultLine));
								nextFound = true;
							} else if (resultLine
									.startsWith(Constants.subsequentBusValStart)) {
								listOfTimes.add(this
										.getSubsequentBusTime(resultLine));
								subsequentFound = true;
							}
							resultLine = resultBr.readLine();
						}
					} else {
						// Server returned unexpected HTTP code.
						System.out.println(Constants.msgNotExpected
								+ conn.getResponseCode());
					}
				} else {
					// Server returned unexpected HTTP code.
					System.out.println(Constants.msgNotExpected
							+ conn.getResponseCode());
				}
			} else {
				// Server returned unexpected HTTP code.
				System.out.println(Constants.msgNotExpected
						+ conn.getResponseCode());
			}
		} catch (final MalformedURLException e) {
			e.printStackTrace();
		} catch (final IOException e) {
			e.printStackTrace();
		}
		return listOfTimes;
	}

	/**
	 * @param res
	 * @return
	 */
	private List<String> getListOfBuses(final List<String> res) {
		final List<String> result = new ArrayList<String>();
		for (final String line : res) {
			if (line.startsWith(Constants.svcLineStart)) {
				// get the service number
				final int idxEnd = line.indexOf(Constants.svcLineIdxEnd);
				final int idxStart = line.lastIndexOf(
						Constants.svcLineIdxStart, idxEnd) + 2;
				result.add(line.substring(idxStart, idxEnd));
			}
		}
		return result;
	}

	/**
	 * @param input
	 * @return
	 */
	private String getNextBusTime(final String input) {
		final int idxStart = input.indexOf(Constants.nextBusValStart)
				+ Constants.nextBusValStart.length();
		final int idxEnd = input.indexOf(Constants.busValBr);
		final String result = input.substring(idxStart, idxEnd).trim();
		return result;
	}

	/**
	 * @param input
	 * @return
	 */
	private String getPostAction(final String input) {
		final int idxStart = input.indexOf(Constants.actionIdxStart);
		final int idxEnd = input.indexOf(Constants.actionIdxEnd);
		final String result = input.substring(idxStart, idxEnd);
		return result;
	}

	/**
	 * @param input
	 * @return
	 */
	private String getSubsequentBusTime(final String input) {
		final int idxStart = input.indexOf(Constants.subsequentBusValStart)
				+ Constants.subsequentBusValStart.length();
		final int idxEnd = input.indexOf(Constants.busValBr);
		final String result = input.substring(idxStart, idxEnd).trim();
		return result;
	}
}
